<template>
  <div class="company-management">
    <!-- 搜索和操作区域 -->
    <div class="search-bar">
      <a-form layout="inline" :model="searchForm">
        <a-form-item label="公司名称">
          <a-input v-model:value="searchForm.companyName" placeholder="请输入公司名称" />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="loadData">搜索</a-button>
          <a-button style="margin-left: 8px" @click="resetSearch">重置</a-button>
        </a-form-item>
      </a-form>
      <a-button type="primary" @click="showModal">新增公司</a-button>
    </div>

    <!-- 数据表格 -->
    <a-table
      :columns="columns"
      :data-source="dataSource"
      :pagination="pagination"
      :loading="loading"
      @change="handleTableChange"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <a-space>
            <a @click="handleEdit(record)">编辑</a>
            <a-popconfirm
              title="确定要删除吗？"
              @confirm="handleDelete(record.id)"
            >
              <a style="color: #ff4d4f">删除</a>
            </a-popconfirm>
          </a-space>
        </template>
      </template>
    </a-table>

    <!-- 新增/编辑模态框 -->
    <a-modal
      v-model:visible="modalVisible"
      :title="modalTitle"
      @ok="handleSubmit"
      @cancel="resetForm"
    >
      <a-form
        ref="formRef"
        :model="formState"
        :rules="rules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
      >
        <a-form-item label="公司名称" name="companyName">
          <a-input v-model:value="formState.companyName" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted, computed } from 'vue'
import { message } from 'ant-design-vue'
import type { TableProps } from 'ant-design-vue'
import {
  saveCompanyUsingPost,
  deleteCompanyUsingPost,
  listUserVoByPageUsingPost1,
  updateConmpanyUsingPost
} from '@/api/companyController'

interface CompanyDTO {
  id?: number
  companyName: string
  contactPerson?: string
  contactPhone?: string
  address?: string
}

// 表格列配置
const columns = [
  {
    title: '公司名称',
    dataIndex: 'companyName',
    key: 'companyName'
  },
  {
    title: '操作',
    key: 'action',
    width: '150px'
  }
]

// 数据状态
const dataSource = ref<CompanyDTO[]>([])
const loading = ref(false)
const modalVisible = ref(false)
const isEdit = ref(false)
const formRef = ref()

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showTotal: (total: number) => `共 ${total} 条`
})

// 表单状态
const formState = reactive<CompanyDTO>({
  companyName: '',
})

// 搜索表单
const searchForm = reactive({
  companyName: ''
})

// 表单验证规则
const rules = {
  companyName: [
    { required: true, message: '请输入公司名称', trigger: 'blur' }
  ],
}

// 初始化加载数据
onMounted(() => {
  loadData()
})

// 加载数据
const loadData = async () => {
  try {
    loading.value = true
    const params = {
      ...searchForm,
      current: pagination.current,
      pageSize: pagination.pageSize
    }

    const res = await listUserVoByPageUsingPost1(params)
    if (res.data.code === 0 && res.data.data) {
      dataSource.value = res.data.data.records || []
      pagination.total = res.data.data.total || 0
    }
  } catch (error) {
    message.error('数据加载失败')
  } finally {
    loading.value = false
  }
}

// 处理分页变化
const handleTableChange: TableProps['onChange'] = (pag) => {
  pagination.current = pag.current!
  pagination.pageSize = pag.pageSize!
  loadData()
}

// 显示新增模态框
const showModal = () => {
  modalVisible.value = true
  isEdit.value = false
}

// 处理编辑
const handleEdit = (record: CompanyDTO) => {
  Object.assign(formState, record)
  modalVisible.value = true
  isEdit.value = true
}

// 处理删除
const handleDelete = async (id: number) => {
  try {
    const res = await deleteCompanyUsingPost({ id })
    if (res.data.code === 0) {
      message.success('删除成功')
      loadData()
    }
  } catch (error) {
    message.error('删除失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()

    if (isEdit.value) {
      await updateConmpanyUsingPost(formState)
      message.success('更新成功')
    } else {
      await saveCompanyUsingPost(formState)
      message.success('新增成功')
    }

    modalVisible.value = false
    resetForm()
    loadData()
  } catch (error) {
    console.error('表单提交失败:', error)
  }
}

// 重置表单
const resetForm = () => {
  formRef.value?.resetFields()
  Object.assign(formState, {
    id: undefined,
    companyName: '',
    contactPerson: '',
    contactPhone: '',
    address: ''
  })
}

// 重置搜索
const resetSearch = () => {
  searchForm.companyName = ''
  loadData()
}

// 计算模态框标题
const modalTitle = computed(() => {
  return isEdit.value ? '编辑公司' : '新增公司'
})
</script>

<style scoped>
.search-bar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 16px;
}
</style>
